package com.rupertjones.globalcron.common.scheduling;

import com.rupertjones.globalcron.common.domain.JobDescriptor;
import com.rupertjones.globalcron.common.domain.JobExecutionLog;
import com.rupertjones.globalcron.common.domain.JobStore;
import org.apache.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;

/**
 * <p>&copy Rupert Jones 2013</p>
 *
 * @author rup
 */
public class MessagingExecutionListener implements JobExecutionListener {
    private static final Logger LOG = Logger.getLogger(MessagingExecutionListener.class);

    private JobStore jobStore;

    private JmsTemplate jmsTemplate;

    @Override
    public void afterExecution(ExecutionContext context) {
        LOG.debug("Sending execution details..");
        JobDescriptor jobDescriptor = context.getJobDescriptor();
        JobDescriptor fresh = jobStore.findById(jobDescriptor.getId());
        JobExecutionLog jobExecutionLog = new JobExecutionLog();
        jobExecutionLog.setTimeTaken(context.getTimeTaken());
        jobExecutionLog.setJob(fresh);
        jobExecutionLog.setExecutedNormally(context.getExecutedNormally());
        jobExecutionLog.setSummary(context.getSummary());
        fresh.updateLastFire(context.getLastFire());
        fresh.updateNextFire(context.getNextFire());
        fresh.addOutput(jobExecutionLog);
        if (jobDescriptor.isSaveOutput()) {
            jobExecutionLog.setOutput(context.getOutput());
        }
        jmsTemplate.convertAndSend(fresh);
    }

    public JobStore getJobStore() {
        return jobStore;
    }

    public void setJobStore(JobStore jobStore) {
        this.jobStore = jobStore;
    }

    public JmsTemplate getJmsTemplate() {
        return jmsTemplate;
    }

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }
}
